<?php
namespace Login\Controller;
use Think\Controller;
//use Think\PHPExcel;

class IndexController extends Controller {
    //ThinkPHP的构造函数
    public function _initialize() {
        header("Content-type:text/html;charset=utf-8");
    }
    //登录页
    public function Index(){
        //phpinfo();exit;
        //如果已登录，则跳转到后台首页
        if(session('admin_id')){
            echo "<script>window.location.href='/'</script>";exit;
        }
        $data['title']='通用后台';
        $this->assign("data", $data);
        $this->display();
    }

    //验证码
    public function show_verify(){
        $Verify =     new \Think\Verify();
        $Verify->imageW = 121;  //图片宽
        $Verify->imageH = 53;  //图片高
        $Verify->fontSize =18;  //字体大小
        $Verify->length   = 4;  //字符数
        $Verify->fontttf = '5.ttf';  //字体
        $Verify->expire = 30;  //有效期
        $Verify->useNoise = false;  //不添加杂点
        $Verify->entry();
    }

    //登录提交
    public function login_post(){
        //验证码验证
        $verify = new \Think\Verify();
        $passcode=addslashes($_POST['passcode']);
        if($verify->check($passcode, '')===false){
            echo "<script>alert('验证码错误');history.go(-1);</script>";exit;
        }
        if(!$_POST['admin_name']||!$_POST['admin_passwd']){
            echo "<script>alert('填写不完整，请您填写完整后提交');history.back(-1);</script>";exit;
        }
        //提交
        $post['admin_name']=I('post.admin_name');
        $post['admin_passwd']=md5(I('post.admin_passwd'));
        //连接user数据库查询
        //$Model=M('Admin','think_',C('DB_CONFIG'));
        $Model=M('Admin');
        $result=$Model->where("admin_name='".$post['admin_name']."' and admin_passwd='".$post['admin_passwd']."'")->count();
        if($result==0){
            echo "<script>alert('用户名/密码错误，请您重新输入');history.back(-1);</script>";exit;
        }
        $admin_id=$Model->where("admin_name='".$post['admin_name']."' and admin_passwd='".$post['admin_passwd']."'")->getField('admin_id');
        $admin_group_id=$Model->where("admin_id=".$admin_id)->getField('admin_group_id');
        //echo $admin_id.'<br />'.$admin_group_id;exit;
        //设置session
        session('admin_id',$admin_id,24*60*60);
        session('admin_group_id',$admin_group_id,24*60*60);
        //echo $_POST['remember'];exit;
        //设置cookie 默认一天
        //if($_POST['remember']==1){
        cookie('admin_id',$admin_id,24*60*60);  //设置cookie时长
        cookie('admin_group_id',$admin_group_id,24*60*60);  //设置cookie时长
        //}
        //dump(session());
        //dump(cookie());exit;
        //print_r(session());exit;
        echo "<script>window.location.href='/'</script>";exit;
    }
    //退出登录
    public function logout(){
        session('admin_id',null);
        session('admin_group_id',null);
        cookie('admin_id',null);
        cookie('admin_group_id',null);
        echo "<script>window.location.href='/login'</script>";exit;
    }

}
